package com.codeduck.test.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @date: 2023/9/16
 */
public class Main {

    public static void main(String[] args) throws IOException {
        String chineseCharacter = "!"; // 要获取编码点的中文字符

        try {
            byte[] utf8Bytes = chineseCharacter.getBytes("GBK"); // 将中文字符编码为UTF-8字节数组

            StringBuilder unicodeCodePoints = new StringBuilder();
            for (byte b : utf8Bytes) {
                unicodeCodePoints.append(String.format("%02X", b & 0xFF)); // 将每个字节的十六进制表示追加到字符串
            }

            System.out.println("UTF-8编码的中文字符对应的Unicode编码点：" + unicodeCodePoints.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void getUnicode(String in) {
        try {
            byte[] bytes = in.getBytes("UTF-8");
            if (bytes.length >= 3) {
                int codePoint = ((bytes[0] & 0xFF) << 16) | ((bytes[1] & 0xFF) << 8) | (bytes[2] & 0xFF);
                System.out.println("UTF-8编码的中文字符对应的Unicode编码点：" + Integer.toHexString(codePoint));
            } else {
                System.out.println("无法获取编码点，字节数组长度不足。");
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toHex(byte b) {
//        %：这表示这是一个格式化标志的起始。
//        0：这表示在输出中使用零来填充字段。如果不足两位，将使用零来填充。
//        2：这表示字段的宽度为2，即生成的十六进制数总是包含两位。
//        X：这表示要将整数值转换为大写十六进制表示法。
        return "0x" + String.format("%02X", b & 0xFF);

    }

    public static long getSum() {
        long sum = 0L;

        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            sum += i;
        }
        return sum;
    }

    public static void readFile(String path) throws IOException {
        try(FileInputStream fis = new FileInputStream(new File(path));
                InputStreamReader isr = new InputStreamReader(fis,"GBK");
            ) {
            char[] buf = new char[1];
            StringBuilder sb = new StringBuilder();
            int size = 0;
            while ((size = isr.read(buf)) != -1) {
                sb.append(buf, 0, size);
            }
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
